package com.itheima.travel.web;

import com.itheima.travel.enums.StatusEnum;
import com.itheima.travel.exception.ProjectException;
import com.itheima.travel.req.UserVo;
import com.itheima.travel.res.ResponseWrap;
import com.itheima.travel.service.UserService;
import com.itheima.travel.utils.EmptyUtil;
import com.itheima.travel.utils.ExceptionsUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/user")
@Log4j2
@CrossOrigin
public class UserController {

    @Autowired
    private UserService service;

    @Autowired
    private HttpSession session;

    @PostMapping("/register")
    public ResponseWrap<Boolean> responseWrap(@RequestBody UserVo userVo) throws ProjectException {

        ResponseWrap<Boolean> responseWrap = null;

        try {
            Boolean flag = service.registerUser(userVo);

            responseWrap = ResponseWrap.<Boolean>builder()
                    .code(StatusEnum.SUCCEED.getCode())
                    .msg(StatusEnum.SUCCEED.getMsg())
                    .operationTime(new Date())
                    .data(flag).build();
        } catch (Exception e) {
            //e.printStackTrace();
            // 记录异常信息到日志文件
            // 将错误信息转成字符串,记录到错误的日志中
            log.error("用户注册：{}", ExceptionsUtil.getStackTraceAsString(e));
            // 生成错误的响应信息
            throw new ProjectException(StatusEnum.REGISTER_USER_FAIL.getCode(),
                    StatusEnum.REGISTER_USER_FAIL.getMsg());
        }

        return responseWrap;
    }

    /**
     * 用户登录
     * @param userVo
     * @return
     * @throws ProjectException
     */
    @PostMapping("/login")
    public ResponseWrap<UserVo> loginUser(@RequestBody UserVo userVo) throws ProjectException {
        try {
            UserVo resultUserVo = service.loginUser(userVo);
            ResponseWrap<UserVo> responseWrap = ResponseWrap.<UserVo>builder()
                    .code(StatusEnum.SUCCEED.getCode())
                    .msg(StatusEnum.SUCCEED.getMsg())
                    .data(resultUserVo)
                    .operationTime(new Date()).build();
            return responseWrap;
        } catch (Exception e) {
            // 记录错误日志
            // 将错误信息转成字符串,记录到错误的日志中
            log.error("用户登录：{}", ExceptionsUtil.getStackTraceAsString(e));
            // 抛出异常
            throw new ProjectException(StatusEnum.LOGIN_USER_FAIL.getCode(),
                    StatusEnum.LOGIN_USER_FAIL.getMsg());
        }
    }

    /**
     * 用户退出
     * @return
     * @throws ProjectException
     */
    @GetMapping("/logout")
    public ResponseWrap<Boolean> loginOutUser() throws ProjectException {
        Boolean flag = true;
        try {
            // 调用service进行退出
            service.loginOutUser();
            return ResponseWrap.<Boolean>builder()
                    .code(StatusEnum.SUCCEED.getCode())
                    .msg(StatusEnum.SUCCEED.getMsg())
                    .operationTime(new Date())
                    .data(flag)
                    .build();
        }catch (Exception e){
            log.error("退出业务：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(StatusEnum.FAIL.getCode(),
                    StatusEnum.FAIL.getMsg());
        }
    }

    /***
     * @description 用户是否登录
     * @return: java.lang.Boolean
     */
    @GetMapping("/islogin")
    public ResponseWrap<Boolean> isLogin() throws ProjectException {
        try {
            Boolean flag = service.isLogin();
            return ResponseWrap.<Boolean>builder()
                    .code(StatusEnum.SUCCEED.getCode())
                    .msg(StatusEnum.SUCCEED.getMsg())
                    .operationTime(new Date())
                    .data(flag)
                    .build();
        }catch (Exception e){
            log.error("是否登录：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(StatusEnum.ISLOGIN_FAIL.getCode(),
                    StatusEnum.ISLOGIN_FAIL.getMsg());
        }
    }

    /***
     * @description 获取当前用户信息
     * @return: java.lang.Boolean
     */
    @GetMapping("/currentUser")
    public ResponseWrap<UserVo> currentUser() throws ProjectException {
        try {
            Object sessionAttribute = session.getAttribute(session.getId());
            if (!EmptyUtil.isNullOrEmpty(sessionAttribute)){
                return ResponseWrap.<UserVo>builder()
                        .code(StatusEnum.SUCCEED.getCode())
                        .msg(StatusEnum.SUCCEED.getMsg())
                        .operationTime(new Date())
                        .data((UserVo) sessionAttribute)
                        .build();
            }else {
                return ResponseWrap.<UserVo>builder()
                        .code(StatusEnum.SUCCEED.getCode())
                        .msg(StatusEnum.SUCCEED.getMsg())
                        .operationTime(new Date())
                        .data(null)
                        .build();
            }
        }catch (Exception e){
            log.error("获取当前登录的用户信息：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(StatusEnum.FAIL.getCode(),
                    StatusEnum.FAIL.getMsg());
        }

    }
}
